package com.rzico.order.receiver;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rzico.account.model.Attach;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.MapLine;
import com.rzico.basics.entity.Receiver;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MapLineService;
import com.rzico.basics.service.ReceiverService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.order.entity.Order;
import com.rzico.order.entity.OrderItem;
import com.rzico.order.entity.Shipping;
import com.rzico.order.entity.Warehouse;
import com.rzico.order.enumx.OrderShippingStatusEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import com.rzico.order.service.OrderItemService;
import com.rzico.order.service.OrderService;
import com.rzico.order.service.ShippingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by icssh on 2020/1/28.
 */
@Controller
public class ShippingReceiver implements ChannelAwareMessageListener {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ReceiverService receiverService;

    @Autowired
    private MapLineService mapLineService;

    @Autowired
    private SysSequenceService sysSequenceService;

    @Autowired
    private ShippingService shippingService;

    @Autowired
    private ShopService shopService;

    @Override
    @RabbitHandler
    @RabbitListener(queues = "queue.order.shipping")
    public void onMessage(Message message, Channel channel) throws Exception {
        boolean success = false;
        try {

            //同一时刻服务器只会发送一条消息给消费者
            channel.basicQos(1);

            String str = new String(message.getBody());
            Attach attachQueue = JSON.parseObject(str,Attach.class);
            try {
                if ("0000".equals(attachQueue.getCode())) {
                    Order order = orderService.selectByPrimaryKey(Long.valueOf(attachQueue.getId()));
                    if (order==null) {
                        return;
                    }
                    if (order.getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId()) && order.getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_UNSHIPPNG.getId())) {
                        Enterprise enterprise = enterpriseService.selectByPrimaryKey(order.getEnterpriseId());
                        Shop shop = null;
                        String shippingEmployeeId = null;
                        if (order.getReceiverId() != null) {
                            Receiver receiver = receiverService.selectByPrimaryKey(order.getReceiverId());
                            if (receiver != null) {
                                MapLine mapLine = mapLineService.findByPoint(enterprise,null, receiver.getLat(), receiver.getLng());
                                if (mapLine != null) {
                                    shop = shopService.selectByPrimaryKey(mapLine.getShopId());
                                    shippingEmployeeId = mapLine.getShippingEmployeeId();
                                }
                            }
                            if (shop == null) {
                                shop = shopService.findByPoint(enterprise, receiver.getLat(), receiver.getLng());
                            }
                        }

                        if (shop != null) {
                            List<OrderItem> itemList = new ArrayList<>();
                            List<OrderItem> orderItemList = orderItemService.getItemList(order.getId());
                            for (OrderItem orderItem : orderItemList) {
                                orderItem.setShippedQuantity(orderItem.getQuantity().subtract(orderItem.getShippedQuantity()));
                                itemList.add(orderItem);
                            }


                            Warehouse warehouse = orderService.shipping(order.getId(), shop.getId(), order.getOrderDate(), order.getWeekTime(), itemList, sysSequenceService.generate("warehouse"));

                            //人工报单时，自动发货

                            if (shippingEmployeeId != null) {
                                Shipping shipping = new Shipping();
                                shipping.setWarehouseId(warehouse.getId());
                                shipping.setEnterpriseId(warehouse.getEnterpriseId());
                                List<Shipping> shippingList = shippingService.select(shipping);
                                for (Shipping shipping1 : shippingList) {
                                    shippingService.dispatch(shipping1.getId(), shop.getId(), shippingEmployeeId);
                                }
                            }
                        }
                    }
                }
                success = true;
            } catch (Exception e) {
                logger.error(str);
                logger.error(e.getMessage());
                success = false;
            }

        } finally {
            if (success) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }

}
